package com.business.dashboard.service.impl;

import com.business.dashboard.dao.NewsArticleDao;
import com.business.dashboard.entity.NewsArticle;
import com.business.dashboard.service.NewsArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新闻文章服务实现类
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@Service
@Transactional
public class NewsArticleServiceImpl implements NewsArticleService {

    @Autowired
    private NewsArticleDao newsArticleDao;

    @Override
    public NewsArticle createArticle(NewsArticle article) {
        // 设置默认值
        if (article.getStatus() == null) {
            article.setStatus("draft");
        }
        if (article.getViewCount() == null) {
            article.setViewCount(0);
        }
        if (article.getLikeCount() == null) {
            article.setLikeCount(0);
        }
        if (article.getCommentCount() == null) {
            article.setCommentCount(0);
        }
        if (article.getShareCount() == null) {
            article.setShareCount(0);
        }
        if (article.getCollectCount() == null) {
            article.setCollectCount(0);
        }
        if (article.getIsFeatured() == null) {
            article.setIsFeatured(0);
        }
        if (article.getIsTop() == null) {
            article.setIsTop(0);
        }
        if (article.getPriority() == null) {
            article.setPriority(0);
        }
        if (article.getDeleted() == null) {
            article.setDeleted(0);
        }
        
        article.setCreatedAt(LocalDateTime.now());
        article.setUpdatedAt(LocalDateTime.now());
        
        newsArticleDao.insert(article);
        log.info("文章创建成功，文章ID: {}, 标题: {}", article.getId(), article.getTitle());
        return article;
    }

    @Override
    public NewsArticle updateArticle(NewsArticle article) {
        if (article.getId() == null) {
            throw new IllegalArgumentException("文章ID不能为空");
        }
        
        article.setUpdatedAt(LocalDateTime.now());
        newsArticleDao.updateById(article);
        log.info("文章更新成功，文章ID: {}", article.getId());
        return article;
    }

    @Override
    public NewsArticle getArticleById(Long id) {
        if (id == null) {
            return null;
        }
        return newsArticleDao.selectById(id);
    }

    @Override
    public boolean deleteArticle(Long id) {
        if (id == null) {
            return false;
        }
        int result = newsArticleDao.deleteById(id);
        if (result > 0) {
            log.info("文章删除成功，文章ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public List<NewsArticle> getArticleList(int page, int size, String keyword, String status, Long categoryId) {
        int offset = (page - 1) * size;
        return newsArticleDao.selectArticleList(offset, size, keyword, status, categoryId);
    }

    @Override
    public long getArticleCount() {
        return newsArticleDao.selectCount(null);
    }

    @Override
    public int getArticleCountByStatus(String status) {
        return newsArticleDao.countByStatus(status);
    }

    @Override
    public boolean publishArticle(Long id) {
        NewsArticle article = getArticleById(id);
        if (article != null) {
            article.setStatus("published");
            article.setPublishTime(LocalDateTime.now());
            article.setUpdatedAt(LocalDateTime.now());
            newsArticleDao.updateById(article);
            log.info("文章发布成功，文章ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public boolean archiveArticle(Long id) {
        NewsArticle article = getArticleById(id);
        if (article != null) {
            article.setStatus("archived");
            article.setUpdatedAt(LocalDateTime.now());
            newsArticleDao.updateById(article);
            log.info("文章归档成功，文章ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public boolean setFeaturedStatus(Long id, Integer isFeatured) {
        NewsArticle article = getArticleById(id);
        if (article != null) {
            article.setIsFeatured(isFeatured);
            article.setUpdatedAt(LocalDateTime.now());
            newsArticleDao.updateById(article);
            log.info("文章推荐状态更新成功，文章ID: {}, 推荐: {}", id, isFeatured);
            return true;
        }
        return false;
    }

    @Override
    public boolean setTopStatus(Long id, Integer isTop) {
        NewsArticle article = getArticleById(id);
        if (article != null) {
            article.setIsTop(isTop);
            article.setUpdatedAt(LocalDateTime.now());
            newsArticleDao.updateById(article);
            log.info("文章置顶状态更新成功，文章ID: {}, 置顶: {}", id, isTop);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateViewCount(Long id) {
        if (id == null) {
            return false;
        }
        int result = newsArticleDao.updateViewCount(id);
        return result > 0;
    }

    @Override
    public List<NewsArticle> getAllNews() {
        return newsArticleDao.selectList(null);
    }

    @Override
    public NewsArticle createNews(NewsArticle news) {
        return createArticle(news);
    }

    @Override
    public NewsArticle updateNews(NewsArticle news) {
        return updateArticle(news);
    }

    @Override
    public boolean deleteNews(Long id) {
        return deleteArticle(id);
    }

    @Override
    public NewsArticle getNewsById(Long id) {
        return getArticleById(id);
    }

    @Override
    public boolean batchUpdateStatus(List<Long> ids, String status) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        int updated = 0;
        for (Long id : ids) {
            NewsArticle article = getArticleById(id);
            if (article != null) {
                article.setStatus(status);
                article.setUpdatedAt(LocalDateTime.now());
                if ("published".equals(status)) {
                    article.setPublishTime(LocalDateTime.now());
                }
                newsArticleDao.updateById(article);
                updated++;
            }
        }
        log.info("批量更新新闻状态成功，更新数量: {}", updated);
        return updated > 0;
    }

    @Override
    public boolean publishNews(Long id) {
        return publishArticle(id);
    }

    @Override
    public boolean unpublishNews(Long id) {
        NewsArticle article = getArticleById(id);
        if (article != null) {
            article.setStatus("draft");
            article.setUpdatedAt(LocalDateTime.now());
            newsArticleDao.updateById(article);
            log.info("取消发布新闻成功，文章ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public Object getNewsStats() {
        // 简单实现新闻统计
        long totalNews = getArticleCount();
        long publishedNews = getArticleCountByStatus("published");
        long draftNews = getArticleCountByStatus("draft");
        long archivedNews = getArticleCountByStatus("archived");

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", totalNews);
        stats.put("published", publishedNews);
        stats.put("draft", draftNews);
        stats.put("archived", archivedNews);
        return stats;
    }

    @Override
    public long getNewsCount() {
        return getArticleCount();
    }

    @Override
    public List<NewsArticle> getPublishedNews(Integer page, Integer limit, String category) {
        try {
            // 使用分页查询已发布的新闻
            int offset = (page - 1) * limit;
            return newsArticleDao.selectPublishedNews(offset, limit, category);
        } catch (Exception e) {
            log.error("获取已发布新闻失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public Long getPublishedNewsCount(String category) {
        try {
            return newsArticleDao.countPublishedNews(category);
        } catch (Exception e) {
            log.error("获取已发布新闻总数失败", e);
            return 0L;
        }
    }

    @Override
    public boolean incrementViewCount(Long id) {
        try {
            newsArticleDao.updateViewCount(id);
            log.debug("增加浏览量成功，文章ID: {}", id);
            return true;
        } catch (Exception e) {
            log.error("增加浏览量失败，文章ID: {}", id, e);
            return false;
        }
    }

    @Override
    public List<NewsArticle> getHotNews(Integer limit) {
        try {
            return newsArticleDao.selectHotNews(limit);
        } catch (Exception e) {
            log.error("获取热门新闻失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<NewsArticle> getLatestNews(Integer limit) {
        try {
            return newsArticleDao.selectLatestNews(limit);
        } catch (Exception e) {
            log.error("获取最新新闻失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<NewsArticle> searchNews(String keyword, Integer page, Integer limit) {
        try {
            int offset = (page - 1) * limit;
            return newsArticleDao.searchNews(keyword, offset, limit);
        } catch (Exception e) {
            log.error("搜索新闻失败，关键词: {}", keyword, e);
            return new ArrayList<>();
        }
    }
}